﻿using NSJL.DAL.DataAccess;
using NSJL.DAL.DataModel.Entities;
using NSJL.DomainModel.Background.System;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using NSJL.DomainModel.Background.Client;
using NSJL.Framework.Utils;
using DJ.ZEF.ThirdParty;

namespace NSJL.Biz.Background.Client
{
    public class CommBiz
    {
        public string CabinetName = null;
        public CommBiz()
        {
            var ini = new IniFile("Config/Config.ini");
            CabinetName = ini.readKey("BoxConfig", "cabinetName");
        }
        public SJLDbContext db = new SJLDbContext();
        public CommonResult Login(string username, string password)
        {
            db = new SJLDbContext();
            var info = db.AdminInfo.Where(p => p.UserName == username).FirstOrDefault();
            if (info == null)
            {
                return new CommonResult() { result = false, message = "用户不存在" };
            }
            if (info.Password != password)
            {
                return new CommonResult() { result = false, message = "密码不正确" };
            }
            return new CommonResult() { result = true };
        }
        public CommonResult EditPassword(string username, string old, string news)
        {
            var db = new SJLDbContext();
            var info = db.AdminInfo.Where(p => p.UserName == username).FirstOrDefault();
            if (info.Password != old)
            {
                return new CommonResult() { result = false, message = "老密码错误" };
            }

            info.Password = news;
            db.SaveChanges();
            return new CommonResult() { result = true, message = "操作成功" };
        }


        public bool InitBoxInfo(int count, string cabname)
        {
            var db = new SJLDbContext();
            var list = db.BoxInfo.OrderBy(p => p.BoxNum).ToList();
            db.BoxInfo.RemoveRange(list);
            for (int i = 1; i <= count; i++)
            {
                var info = new BoxInfo();
                info.Id = Guid.NewGuid().ToString("N");
                info.CreateTime = DateTime.Now;
                info.BoxNum = i;
                info.BoxType = "小";
                info.IsFree = true;
                info.CabName = cabname;
                db.BoxInfo.Add(info);
            }
            db.SaveChanges();
            return true;
        }



        public List<OpenBoxInfo> GetOpenBoxList(DateTime? start, DateTime? end)
        {
            db = new SJLDbContext();
            var sql = db.OpenBoxInfo.AsQueryable();
            if (start != null)
            {
                sql = sql.Where(p => p.InTime > start);
            }
            if (end != null)
            {
                sql = sql.Where(p => p.OutTime < end);
            }

            return sql.OrderByDescending(p => p.InTime).ToList();


        }

        public bool AddOpenBoxInfo(int boxNum,string userName,string code,bool flag = false)
        {
            try
            {
                db = new SJLDbContext();
                if (!flag)
                {
                    OpenBoxInfo info = new OpenBoxInfo();
                    info.Id = Guid.NewGuid().ToString("N");
                    info.Name = userName;
                    info.BoxNum = boxNum;
                    info.InTime = DateTime.Now;
                    info.Code = code;
                    info.CabName = CabinetName;
                    db.OpenBoxInfo.Add(info);
                }
                else
                {
                    List<OpenBoxInfo> lists = db.OpenBoxInfo.Where(p => p.OutTime == null && p.BoxNum == boxNum).ToList();
                    if (!string.IsNullOrEmpty(userName))
                    {
                        lists = lists.Where(p => p.Name == userName).ToList();
                    }
                    if (!string.IsNullOrEmpty(code))
                    {
                        lists = lists.Where(p => p.Code == code).ToList();
                    }
                    OpenBoxInfo openBoxInfo = lists.OrderByDescending(p => p.InTime).FirstOrDefault();
                    openBoxInfo.OutTime = DateTime.Now;
                }

                db.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                TextLogUtil.Error($"添加失败:{ex.Message}");
                return false;
            }
        }



        public List<AdminLogInfo> GetAdminLogList(DateTime? start, DateTime? end)
        {
            var db = new SJLDbContext();
            if (start == null)
            {
                return db.AdminLogInfo.OrderByDescending(p => p.CreateTime).ToList();
            }
            else
            {
                return db.AdminLogInfo.Where(p => p.CreateTime >= start && p.CreateTime <= end).OrderByDescending(p => p.CreateTime).ToList();
            }
        }
        public List<BoxInfo> GetBoxList()
        {
            var db = new SJLDbContext();
            var list = db.BoxInfo.Where(p => p.CabName == CabinetName).OrderBy(p => p.BoxNum).ToList();
            return list;
        }
        
        public BoxInfo GetBoxListWithType(string type)
        {
            var db = new SJLDbContext();
            var box = db.BoxInfo.Where(p => p.CabName == CabinetName && p.BoxType == type &&p.IsLock != true && p.IsFree == true).OrderBy(p => p.BoxNum).FirstOrDefault();
            return box;
        }
        
        public bool GetBoxListWithQrCode(string qrCode)
        {
            var db = new SJLDbContext();
            var b = db.BoxInfo.Any(p => p.CabName == CabinetName && p.QrCode == qrCode);
            return b;
        }
        
        public int GetBoxNumWithQrCode(string qrCode)
        {
            var db = new SJLDbContext();
            var num = db.BoxInfo.Where(p => p.CabName == CabinetName && p.QrCode == qrCode).FirstOrDefault();
            if (num != null)
            {
                return num.BoxNum;
            }
            return 0;
        }
        
        public bool GetBoxListWithUserId(string userId)
        {
            var db = new SJLDbContext();
            var b = db.BoxInfo.Any(p => p.CabName == CabinetName && p.UserId == userId);
            return b;
        }
        
        public int GetBoxNumWithUserId(string userId)
        {
            var db = new SJLDbContext();
            var b = db.BoxInfo.Where(p => p.CabName == CabinetName && p.UserId == userId).FirstOrDefault();
            if (b != null)
            {
                return b.BoxNum;
            }
            return 0;
        }
        public bool GetBoxState(int boxNum)
        {
            var db = new SJLDbContext();
            var b = (bool)db.BoxInfo.Where(p => p.CabName == CabinetName && p.BoxNum == boxNum).FirstOrDefault().IsLock;
            return b;
        }
        public List<GetBoxWithExcel> GetBoxListWithExcel()
        {
            var db = new SJLDbContext();
            var list = db.BoxInfo.Where(p => p.CabName == CabinetName).OrderBy(p => p.BoxNum).ToList();
            return AutoMapper.Mapper.DynamicMap<List<GetBoxWithExcel>>(list);
        }
        public List<GetBoxInfo> GetBoxListWithUserId()
        {
            db = new SJLDbContext();
            var info = from a in db.BoxInfo
                       join b in db.UserInfo on a.UserId equals b.Id into temp
                       from b in temp.DefaultIfEmpty()
                       where a.CabName == CabinetName
                       select new GetBoxInfo()
                       {
                           Id = a.Id,
                           CabName = a.CabName,
                           BoxNum = a.BoxNum,
                           IsLock = a.IsLock,
                           UserId = a.UserId,
                           IsFree = a.IsFree,
                           Name = b.Name,
                           BoxType = a.BoxType,
                           CardCode = b.CardCode,
                           QrCode = a.QrCode
                       };
            return info.OrderBy(p => p.BoxNum).ToList();
        }
        public List<GetBoxInfo> GetBoxListWithBoxId(List<int> blist, string userid)
        {
            db = new SJLDbContext();
            var info = from a in db.BoxInfo
                       join b in db.UserInfo on a.UserId equals b.Id into temp
                       from b in temp.DefaultIfEmpty()
                       where a.CabName == CabinetName && a.IsLock != true && (a.UserId == null || a.UserId == "" || a.UserId == userid)
                       select new GetBoxInfo()
                       {
                           Id = a.Id,
                           CabName = a.CabName,
                           BoxNum = a.BoxNum,
                           IsLock = a.IsLock,
                           UserId = a.UserId,
                           IsFree = a.IsFree,
                           BoxType = a.BoxType,
                       };
            var list = info.OrderBy(p => p.BoxNum).ToList();
            return list.Where(p => blist.Contains(p.BoxNum)).ToList();
        }
        public List<GetBoxInfo> GetBoxListWithUserIdClient(string userid)
        {
            db = new SJLDbContext();
            var info = from a in db.BoxInfo
                       join b in db.UserInfo on a.UserId equals b.Id into temp
                       from b in temp.DefaultIfEmpty()
                       where a.CabName == CabinetName && a.IsLock != true && a.UserId == userid
                       select new GetBoxInfo()
                       {
                           Id = a.Id,
                           CabName = a.CabName,
                           BoxNum = a.BoxNum,
                           IsLock = a.IsLock,
                           UserId = a.UserId,
                           IsFree = a.IsFree,
                           BoxType = a.BoxType,
                       };
            var list = info.OrderBy(p => p.BoxNum).ToList();
            return list;
        }
      
        public List<GetGoodsList> GetBoxListWithLin()
        {
            var db = new SJLDbContext();
            var list = db.BoxInfo.OrderBy(p => p.BoxNum).ToList();
            return AutoMapper.Mapper.DynamicMap<List<GetGoodsList>>(list);
        }
        public bool EditAdminLogInfo(string str, string adminname)
        {
            var db = new SJLDbContext();
            var info = new AdminLogInfo();
            info.UserName = adminname;
            info.CreateTime = DateTime.Now;
            info.Content = str;
            info.Id = Guid.NewGuid().ToString("N");
            info.CabName = CabinetName;
            db.AdminLogInfo.Add(info);
            db.SaveChanges();
            return true;
        }
        public CommonResult ClearBoxList(List<int> tlist)
        {
            var db = new SJLDbContext();
            var list = db.BoxInfo.Where(p => p.CabName == CabinetName).ToList();
            foreach (var item in tlist)
            {
                var info = list.Where(p => p.BoxNum == item).FirstOrDefault();
                string userId = info.UserId;
                string qrCode = info.QrCode;
                info.IsFree = true;
                info.UserId = null;
                info.QrCode = null;
                info.IsLock = false;
                string code = null;
                if (!string.IsNullOrEmpty(userId))
                {
                    UserInfo userInfos = db.UserInfo.Where(p => p.Id == userId).FirstOrDefault();
                    code = userInfos.CardCode;
                }
                if (!string.IsNullOrEmpty(qrCode))
                {
                    code = qrCode;
                }
                if (!string.IsNullOrEmpty(code))
                {
                    List<OpenBoxInfo> lists = db.OpenBoxInfo.Where(p => p.BoxNum == item && p.Code == code && p.OutTime == null).ToList();
                    foreach (var item1 in lists)
                    {
                        item1.OutTime = DateTime.Now;
                    }
                }
            }
            db.SaveChanges();
            return new CommonResult() { result = true, message = "操作成功" };
        }
        public bool AllClearBoxinfo()
        {
            var db = new SJLDbContext();
            var list = db.BoxInfo.OrderBy(p => p.BoxNum).ToList();
            foreach (var item in list)
            {
                string userId = item.UserId;
                string qrCode = item.QrCode;
                item.IsFree = true;
                item.UserId = null;
                item.QrCode = null;
                item.IsLock = false;
                string code = null;
                if (!string.IsNullOrEmpty(userId))
                {
                    UserInfo userInfos = db.UserInfo.Where(p => p.Id == userId).FirstOrDefault();
                    code = userInfos.CardCode;
                }
                if (!string.IsNullOrEmpty(qrCode))
                {
                    code = qrCode;
                }
                if (!string.IsNullOrEmpty(code))
                {
                    List<OpenBoxInfo> lists = db.OpenBoxInfo.Where(p => p.BoxNum == item.BoxNum && p.Code == code && p.OutTime == null).ToList();
                    foreach (var item1 in lists)
                    {
                        item1.OutTime = DateTime.Now;
                    }
                }
            }
            db.SaveChanges();
            return true;
        }
        public bool LockBoxList(List<int> tlist)
        {
            var db = new SJLDbContext();
            var list = db.BoxInfo.Where(p => p.CabName == CabinetName).ToList();
            foreach (var item in tlist)
            {
                var info = list.Where(p => p.BoxNum == item).FirstOrDefault();
                info.IsLock = true;
            }
            db.SaveChanges();
            return true;
        }
        public bool UnLockBoxList(List<int> tlist)
        {
            var db = new SJLDbContext();
            var list = db.BoxInfo.Where(p => p.CabName == CabinetName).ToList();
            foreach (var item in tlist)
            {
                var info = list.Where(p => p.BoxNum == item).FirstOrDefault();
                info.IsLock = false;
            }
            db.SaveChanges();
            return true;
        }
        public List<UserInfo> GetUserList(string name)
        {
            var db = new SJLDbContext();
            if (string.IsNullOrWhiteSpace(name))
            {
                var list = db.UserInfo.OrderByDescending(p => p.CreateTime).ToList();

                return AutoMapper.Mapper.DynamicMap<List<UserInfo>>(list);
            }
            else
            {
                var list = db.UserInfo.Where(p => p.Name.Contains(name)).OrderByDescending(p => p.CreateTime).ToList();
                return AutoMapper.Mapper.DynamicMap<List<UserInfo>>(list);
            }
        }
        
        
        public UserInfo GetUserInfoWithCode(string cardCode)
        {
            var db = new SJLDbContext();
            var list = db.UserInfo.Where(p=>p.CardCode == cardCode).OrderByDescending(p => p.CreateTime).ToList();
            return list.FirstOrDefault();
           
        }
        public bool DelUserInfo(string id)
        {
            db = new SJLDbContext();
            var info = db.UserInfo.Where(p => p.Id == id).FirstOrDefault();
            db.UserInfo.Remove(info);
            db.SaveChanges();
            return true;
        }
        public CommonResult EditUserInfo(string id, string name, string code)
        {
            var db = new SJLDbContext();
            var list = db.UserInfo.OrderByDescending(p => p.CreateTime).ToList();
            if (string.IsNullOrWhiteSpace(id))
            {
                if (db.UserInfo.Any(p => p.Name == name))
                {
                    return new CommonResult() { result = false, message = "用户名已存在，无法添加" };
                }
                if (db.UserInfo.Any(p => p.CardCode == code))
                {
                    return new CommonResult() { result = false, message = "卡号已存在，无法添加" };
                }
                var info = new UserInfo();
                info.Id = Guid.NewGuid().ToString("N");
                info.CreateTime = DateTime.Now;
                info.UpdateTime = DateTime.Now;
                info.Name = name;
                info.CardCode = code;
                db.UserInfo.Add(info);
            }
            else
            {
                var user = db.UserInfo.Where(p => p.Id == id).FirstOrDefault();

                if (db.UserInfo.Any(p => p.Name != name) && user.CardCode == code)
                {
                    return new CommonResult() { result = false, message = "卡号已存在，无法添加" };
                }
                user.Name = name;
                user.CardCode = code;
                user.UpdateTime = DateTime.Now;
            }
            db.SaveChanges();

            return new CommonResult() { result = true, message = "操作成功" };
        }
      

        public CommonResult EditCabinet(string name)
        {
            db = new SJLDbContext();
            if (db.CabinetInfo.Any(p => p.Name == name))
            {
                return new CommonResult() { result = false, message = "柜号名已存在" };
            }
            var info = new CabinetInfo();
            info.Id = Guid.NewGuid().ToString("N");
            info.Name = name;
            info.CreateTime = DateTime.Now;
            db.CabinetInfo.Add(info);
            db.SaveChanges();
            return new CommonResult() { result = true };
        }
        public List<CabinetInfo> GetCabinetList()
        {
            db = new SJLDbContext();
            return db.CabinetInfo.OrderByDescending(p => p.CreateTime).ToList();
        }
        public bool DelCabinet(string name)
        {
            db = new SJLDbContext();
            var info = db.CabinetInfo.Where(p => p.Name == name).FirstOrDefault();
            db.CabinetInfo.Remove(info);
            db.SaveChanges();
            return true;
        }
        public bool IsCabinet(string name)
        {
            db = new SJLDbContext();
            return db.CabinetInfo.Any(p => p.Name == name);
        }

      
      
        private int num = 0;

    




    


        public List<GetBoxWithExcelOther> GetUserListWithExcel()
        {
            db = new SJLDbContext();
            var list = db.UserInfo.OrderByDescending(p => p.CreateTime).ToList();
            return AutoMapper.Mapper.DynamicMap<List<GetBoxWithExcelOther>>(list);
        }
        public void ImportExcelWithUserInfo(DataTable dt)
        {
            db = new SJLDbContext();
            var list = db.UserInfo.ToList();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var temp = (string)dt.Rows[i][0];
                var temp1 = (string)(dt.Rows[i][1] == DBNull.Value ? "" : dt.Rows[i][1]);
                var temp2 = (string)(dt.Rows[i][2] == DBNull.Value ? "" : dt.Rows[i][2]);
                var temp3 = (string)(dt.Rows[i][3] == DBNull.Value ? "" : dt.Rows[i][3]);
                var temp4 = (string)(dt.Rows[i][4] == DBNull.Value ? "" : dt.Rows[i][4]);

                if (!string.IsNullOrWhiteSpace(temp))
                {
                    if (list.Any(p => p.CardCode == temp3))
                    {
                        continue;
                    }
                    var info = list.Where(p => p.Id == temp).FirstOrDefault();
                    if (info != null)
                    {
                        info.Name = temp1;
                        info.CardCode = temp3;
                    }
                    else
                    {
                        var model = new UserInfo();
                        model.Id = temp;
                        model.CreateTime = DateTime.Now;
                        model.Name = temp1;
                        model.CardCode = temp3;
                        db.UserInfo.Add(model);
                    }
                }
            }
            db.SaveChanges();

        }
     
        public void SetBoxTypeList(List<int> tlist, string type)
        {
            var db = new SJLDbContext();
            var list = db.BoxInfo.Where(p => p.CabName == CabinetName).ToList();
            foreach (var item in tlist)
            {
                var info = list.Where(p => p.BoxNum == item).FirstOrDefault();
                info.BoxType = type;
            }
            db.SaveChanges();
        }

        

      


        #region old
        public AdminInfo GetAdminInfo()
        {
            var db = new SJLDbContext();
            return db.AdminInfo.FirstOrDefault();
        }

        public BoxInfo GetBoxInfo(int boxnum)
        {
            var db = new SJLDbContext();
            var info = db.BoxInfo.Where(p => p.BoxNum == boxnum).FirstOrDefault();
            return info;
        }
        
        public void EditBoxInfo(int boxnum,bool isfree,string card,string QrCode)
        {
            var db = new SJLDbContext();
            var info = db.BoxInfo.Where(p => p.BoxNum == boxnum).FirstOrDefault();
            info.IsFree = isfree;
            info.UserId = card;
            info.QrCode = QrCode;
            info.UpdateTime = DateTime.Now;
            db.SaveChanges();
        }
        #endregion


        #region 
        public List<AuthenticationInfo> GetAuthInfo(string pStr = null)
        {
            var db = new SJLDbContext();
            var info = db.AuthenticationInfo.ToList();
            if (!string.IsNullOrEmpty(pStr))
            {
                return info.Where(p=>p.p == pStr).ToList();
            }
            return info;
        }



        public bool AddAuthInfo(AuthenticationInfo info)
        {
            var db = new SJLDbContext();
            List<AuthenticationInfo> authenticationInfos = db.AuthenticationInfo.Where(p => p.p == info.p).ToList();
            db.AuthenticationInfo.RemoveRange(authenticationInfos);
            db.AuthenticationInfo.Add(info);
            int v = db.SaveChanges();
            if (v > 0)
            {
                return true;
            }
            return false;
        }
        #endregion


        #region 异常日志
        public List<FailInfo> GetFailInfo(DateTime? start, DateTime? end)
        {
            db = new SJLDbContext();
            var sql = db.FailInfo.AsQueryable();

            if (start != null)
            {
                sql = sql.Where(p => p.CreateTime > start);
            }
            if (end != null)
            {
                sql = sql.Where(p => p.CreateTime < end);
            }

            return sql.OrderByDescending(p => p.CreateTime).ToList();


        }
        
        
        public void AddFailInfo(string msg)
        {
            var db = new SJLDbContext();
            FailInfo info = new FailInfo();
            info.Id = Guid.NewGuid().ToString("N");
            info.CreateTime = DateTime.Now;
            info.Msg = msg;
            db.FailInfo.Add(info);
            db.SaveChanges();
        }
        #endregion


        #region 设备管理
        public List<DevicesInfo> GetDevicesInfo(string name = null)
        {
            db = new SJLDbContext();
            var lists = db.DevicesInfo.ToList();
            if (!string.IsNullOrEmpty(name))
            {
                lists = lists.Where(p=>p.DeviceName.Contains(name)).ToList();
            }
            return lists;
        }
        public string EditDevicesInfo(string name,string com,string baud,string type, string id = null, int count = 0)
        {
            db = new SJLDbContext();
            if (string.IsNullOrEmpty(id))
            {
                bool v = db.DevicesInfo.Any(p =>p.DeviceName == name || p.COM == com);
                if (v)
                {
                    return "新增失败，设备名称已存在或者COM口冲突";
                }
                DevicesInfo dev = new DevicesInfo();
                dev.Id = Guid.NewGuid().ToString("N");
                dev.DeviceName = name;
                dev.COM = com;
                dev.Baud = baud;
                dev.Type = type;
                dev.CabName = CabinetName;
                dev.Count = 0;
                dev.UpdateTime = DateTime.Now;
                dev.CreateTime = DateTime.Now;
                db.DevicesInfo.Add(dev);
                db.SaveChanges();
                return "新增成功";
            }
            else
            {
                DevicesInfo device = db.DevicesInfo.Where(p => p.Id == id).FirstOrDefault();
                if (device != null)
                {
                    bool v = db.DevicesInfo.Any(p => p.Id != id && (p.DeviceName.Contains(name) || p.COM == com));
                    if (v)
                    {
                        return "编辑失败，设备名称已存在或者COM口冲突";
                    }
                    device.COM = com;
                    device.Baud = baud;
                    device.Type = type;
                    device.Count = count;
                    device.UpdateTime = DateTime.Now;
                    db.SaveChanges();
                    return "编辑成功";
                }
            }
    
            return null;
        }

        public void DeleteDevices(string id)
        {
            db = new SJLDbContext();
            DevicesInfo devicesInfo = db.DevicesInfo.Where(p => p.Id == id).FirstOrDefault();
            if (devicesInfo != null)
            {
                db.DevicesInfo.Remove(devicesInfo);
                db.SaveChanges();
            }
        }
        #endregion



    }
}
